package com.cqhz.quwan.ui.buy

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.UserInfoBean
import com.cqhz.quwan.mvp.mine.*
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.activity.RechargeActivity
import com.cqhz.quwan.ui.mine.PayPasswordActivity
import com.cqhz.quwan.util.PayEventObserver
import com.cqhz.quwan.util.PayResult
import com.cqhz.quwan.util.format
import kotlinx.android.synthetic.main.activity_payment.*
import javax.inject.Inject

class PaymentActivity : GoBackActivity(), AlipayContract.View, PaymentContract.View {

    private var payMethodIsBalance: Boolean = false
    @Inject
    lateinit var paymentPresenter: PaymentPresenter
    private var userInfoBean: UserInfoBean? = null
    private lateinit var tipAlterDialog1: AlertDialog
    private lateinit var tipAlterDialog2: AlertDialog

    companion object {
        const val DO_PAY = 0x11
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        this.userInfoBean = userInfoBean
    }
    override fun titleBarText(): String? {
        return "支付"
    }

    override fun layout(): Int {
        return R.layout.activity_payment
    }

    private fun createTipAlterDialog2(): AlertDialog {
        return AlertDialog.Builder(this)
                .setTitle("提示！")
                .setMessage("当前账户余额不足，是否充值")
                .setPositiveButton("去充值", { _, _ ->
                    startActivity(Intent(this, RechargeActivity::class.java))
                })
                .setNegativeButton("取消", { _, _ ->

                })
                .create()
    }

    private fun createTipAlterDialog1(): AlertDialog {
        return AlertDialog.Builder(this)
                .setTitle("提示！")
                .setMessage("当前还没有设置支付密码")
                .setPositiveButton("去设置", { _, _ ->
                    startActivity(Intent(this, PayPasswordActivity::class.java))
                })
                .setNegativeButton("取消", { _, _ ->

                })
                .create()
    }

    override fun initView() {
        paymentPresenter.attachView(this)
        tipAlterDialog1 = createTipAlterDialog1()
        tipAlterDialog2 = createTipAlterDialog2()

        val amount = intent.getDoubleExtra(KeyContract.Amount, 0.0)
        val actualAmount = intent.getDoubleExtra(KeyContract.ActualAmount, 0.0)
        val orderId = intent.getStringExtra(KeyContract.OrderId)
        val periodNum = intent.getStringExtra(KeyContract.PeriodNum)
        val lotteryName = intent.getStringExtra(KeyContract.LotteryName)
        val infoText = "$lotteryName ${if (periodNum == null) "" else "第${periodNum}期"}"

        tv_lottery_info.text = infoText
        tv_payment_amount.text = amount.format()
        tv_payment_actual_amount.text = actualAmount.format()
        action_pay.setOnClickListener {
            if (payMethodIsBalance && userInfoBean != null) {
                val isResetPayPassword = userInfoBean?.payPwd == "1"
                val hasBalance = (userInfoBean?.balance ?: "0.0").toDouble() > 0.0
                if (!isResetPayPassword) {
//                    tipAlterDialog1.show()
                } else if (!hasBalance) {
                    tipAlterDialog2.show()
                } else {
                    val intent = Intent(this, DoPayActivity::class.java)
                    intent.putExtra(KeyContract.ActualAmount, actualAmount)
                    intent.putExtra(KeyContract.OrderId, orderId)
                    startActivityForResult(intent, DO_PAY)
                }
            } else {
                paymentPresenter.aliPay(orderId)
            }
        }
        cb_payment_method_balance.setOnClickListener {
            resetPayMethodCb(true)
        }
        cb_payment_method_alipay.setOnClickListener {
            resetPayMethodCb(false)
        }
    }

    private fun resetPayMethodCb(isBalance: Boolean) {
        payMethodIsBalance = isBalance
        cb_payment_method_balance.isChecked = isBalance
        cb_payment_method_alipay.isChecked = !isBalance
    }

    override fun alipayCallBack() {
        PayEventObserver.pushPayFinish()
        finish()
    }

    override fun alipayFail(payResult: PayResult) {
        showToast(payResult.memo)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DO_PAY && resultCode == Activity.RESULT_OK) {
            PayEventObserver.pushPayFinish()
            finish()
        }
    }

    override fun onDestroy() {
        paymentPresenter.detachView()
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        val loginInfo = APP.get()?.loginInfo
        if (loginInfo != null) {
            showLoading("正在加载数据...")
            paymentPresenter.getUserInfo(loginInfo.userId!!)
        }
    }
}